/**
 * @(#)CommonAssignmentHandler.java 2009-11-16
 *   
 * Copyright  (c) 2009-2010 Wilmar IT Service,  Inc.   
 * All  rights  reserved.   
 * TODO
 */

package com.wilmar.process.core.assignment;

import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;
import org.jbpm.api.model.OpenExecution;
import org.jbpm.api.task.Assignable;
import org.jbpm.api.task.AssignmentHandler;

import com.wilmar.process.entity.Organization;
import com.wilmar.process.entity.ProcessParticipant;
import com.wilmar.process.entity.Role;
import com.wilmar.process.entity.User;

/**
 * 通用的任务分配器，使用通常的人员，组织，角色，找到相应的人员信息，并将任务分配进任务池中，等待实际处理人来接收
 * 
 * @author makubex Email:makubexnet@gmail.com
 * @version 1.0.0
 */
public class CommonAssignmentHandlerImpl extends AbstractAssignmentHandlerImpl
		implements AssignmentHandler {

	/**
	 * @serialField
	 */
	private static final long serialVersionUID = 4184382603098680748L;
	private static Logger log = Logger
			.getLogger(CommonAssignmentHandlerImpl.class);

	private Set<String> userSet;
	private Set<String> roleSet;
	private Set<String> organizationSet;

	/**
	 * @see org.jbpm.api.task.AssignmentHandler#assign(org.jbpm.api.task.Assignable,
	 *      org.jbpm.api.model.OpenExecution)
	 */
	public void assign(Assignable assignable, OpenExecution openExecution)
			throws Exception {
		ProcessParticipant participant = new ProcessParticipant();
		if (userSet != null && !userSet.isEmpty()) {
			Set<User> c_userSet = new HashSet<User>();
			for (String userid : userSet)
				c_userSet.add(new User(userid));
			participant.setUserSet(c_userSet);
		}
		if (roleSet != null && !roleSet.isEmpty()) {
			Set<Role> c_roleSet = new HashSet<Role>();
			for (String roleid : roleSet)
				c_roleSet.add(new Role(roleid));
			participant.setRoleSet(c_roleSet);
		}
		if (organizationSet != null && !organizationSet.isEmpty()) {
			Set<Organization> c_orgSet = new HashSet<Organization>();
			for (String orgid : organizationSet)
				c_orgSet.add(new Organization(orgid));
			participant.setOrganizationSet(c_orgSet);
		}
		if (super.filter != null) {
			log.debug("Filting participant...");
			participant = super.filter.doFilter(participant, openExecution
					.getVariables(), openExecution);
		}
		super.appendParticipant(assignable, participant);
		log.debug("Sending email...");
		super.sendEmail(openExecution, participant);
	}

}
